/**
 * 测试报告生成器
 * 将JSON测试结果转换为HTML报告
 */

const fs = require('fs')
const path = require('path')

// 配置
const config = {
  inputFile: 'test-results.json',
  outputFile: 'test-report.html',
}

// 生成HTML报告
function generateReport() {
  try {
    // 读取测试结果
    const resultPath = path.join(__dirname, config.inputFile)
    if (!fs.existsSync(resultPath)) {
      console.error(`测试结果文件不存在: ${resultPath}`)
      return
    }

    const results = JSON.parse(fs.readFileSync(resultPath, 'utf8'))

    // 生成HTML
    let html

    // 检查服务器是否在线
    if (results.serverStatus === 'offline') {
      html = `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>API稳定性测试报告 - 服务器离线</title>
  <style>
    body {
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      line-height: 1.6;
      color: #333;
      max-width: 1200px;
      margin: 0 auto;
      padding: 20px;
      background-color: #f5f5f5;
    }
    .container {
      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      padding: 30px;
      text-align: center;
    }
    h1, h2, h3 {
      color: #2c3e50;
    }
    h1 {
      margin-bottom: 30px;
      padding-bottom: 15px;
      border-bottom: 2px solid #eee;
    }
    .error-icon {
      font-size: 80px;
      color: #dc3545;
      margin: 30px 0;
    }
    .error-message {
      font-size: 24px;
      color: #dc3545;
      margin-bottom: 30px;
    }
    .suggestion {
      font-size: 18px;
      color: #6c757d;
      margin-bottom: 40px;
    }
    .meta-info {
      font-size: 12px;
      color: #6c757d;
      text-align: right;
      margin-top: 40px;
    }
  </style>
</head>
<body>
  <div class="container">
    <h1>API稳定性测试报告</h1>
    
    <div class="error-icon">⚠️</div>
    <div class="error-message">服务器离线或无法连接</div>
    <div class="suggestion">
      <p>无法连接到API服务器。请确保服务器正在运行，并且可以通过以下地址访问：</p>
      <p><strong>http://localhost:7204</strong></p>
      <p>启动服务器后，请重新运行测试。</p>
    </div>

    <div class="meta-info">
      <p>测试时间: ${results.timestamp}</p>
    </div>
  </div>
</body>
</html>
      `
    } else {
      // 计算成功率和其他指标，避免除以零的情况
      const successRate =
        results.totalRequests > 0
          ? (
              (results.successfulRequests / results.totalRequests) *
              100
            ).toFixed(2)
          : 'N/A'

      const formatValidRate =
        results.formatValidation.valid + results.formatValidation.invalid > 0
          ? (
              (results.formatValidation.valid /
                (results.formatValidation.valid +
                  results.formatValidation.invalid)) *
              100
            ).toFixed(2)
          : 'N/A'

      const errorHandlingRate =
        results.errorHandling.valid + results.errorHandling.invalid > 0
          ? (
              (results.errorHandling.valid /
                (results.errorHandling.valid + results.errorHandling.invalid)) *
              100
            ).toFixed(2)
          : 'N/A'

      const avgDuration =
        results.totalRequests > 0 && !isNaN(results.averageDuration)
          ? results.averageDuration.toFixed(2)
          : 'N/A'

      html = `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>API稳定性测试报告</title>
  <style>
    body {
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      line-height: 1.6;
      color: #333;
      max-width: 1200px;
      margin: 0 auto;
      padding: 20px;
      background-color: #f5f5f5;
    }
    .container {
      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      padding: 30px;
    }
    h1, h2, h3 {
      color: #2c3e50;
    }
    h1 {
      text-align: center;
      margin-bottom: 30px;
      padding-bottom: 15px;
      border-bottom: 2px solid #eee;
    }
    .summary-box {
      display: flex;
      flex-wrap: wrap;
      gap: 20px;
      margin-bottom: 30px;
    }
    .summary-item {
      flex: 1;
      min-width: 200px;
      background-color: #f8f9fa;
      border-radius: 6px;
      padding: 15px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    }
    .summary-item h3 {
      margin-top: 0;
      font-size: 16px;
      color: #6c757d;
    }
    .summary-item p {
      font-size: 24px;
      font-weight: bold;
      margin: 10px 0 0;
      color: #343a40;
    }
    .success {
      color: #28a745;
    }
    .warning {
      color: #ffc107;
    }
    .danger {
      color: #dc3545;
    }
    table {
      width: 100%;
      border-collapse: collapse;
      margin: 20px 0;
      font-size: 14px;
    }
    th, td {
      padding: 12px 15px;
      text-align: left;
      border-bottom: 1px solid #ddd;
    }
    th {
      background-color: #f8f9fa;
      font-weight: 600;
    }
    tr:hover {
      background-color: #f1f1f1;
    }
    .chart-container {
      display: flex;
      flex-wrap: wrap;
      gap: 20px;
      margin: 30px 0;
    }
    .chart {
      flex: 1;
      min-width: 300px;
      height: 300px;
      background-color: #fff;
      border-radius: 6px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
      padding: 15px;
    }
    .progress-bar {
      height: 20px;
      background-color: #e9ecef;
      border-radius: 4px;
      margin-top: 8px;
      overflow: hidden;
    }
    .progress-fill {
      height: 100%;
      background-color: #007bff;
      border-radius: 4px;
    }
    .meta-info {
      font-size: 12px;
      color: #6c757d;
      text-align: right;
      margin-top: 40px;
    }
  </style>
</head>
<body>
  <div class="container">
    <h1>API稳定性测试报告</h1>
    
    <div class="summary-box">
      <div class="summary-item">
        <h3>总请求数</h3>
        <p>${results.totalRequests}</p>
      </div>
      <div class="summary-item">
        <h3>成功率</h3>
        <p class="${successRate !== 'N/A' ? getSuccessRateClass(parseFloat(successRate)) : ''}">
          ${successRate}${successRate !== 'N/A' ? '%' : ''}
        </p>
      </div>
      <div class="summary-item">
        <h3>平均响应时间</h3>
        <p>${avgDuration}${avgDuration !== 'N/A' ? ' ms' : ''}</p>
      </div>
      <div class="summary-item">
        <h3>格式验证通过率</h3>
        <p class="${formatValidRate !== 'N/A' ? getSuccessRateClass(parseFloat(formatValidRate)) : ''}">
          ${formatValidRate}${formatValidRate !== 'N/A' ? '%' : ''}
        </p>
      </div>
      <div class="summary-item">
        <h3>错误处理正确率</h3>
        <p class="${errorHandlingRate !== 'N/A' ? getSuccessRateClass(parseFloat(errorHandlingRate)) : ''}">
          ${errorHandlingRate}${errorHandlingRate !== 'N/A' ? '%' : ''}
        </p>
      </div>
    </div>

    <h2>端点性能</h2>
    <table>
      <thead>
        <tr>
          <th>端点</th>
          <th>请求数</th>
          <th>成功率</th>
          <th>格式有效率</th>
          <th>平均响应时间</th>
        </tr>
      </thead>
      <tbody>
        ${generateEndpointRows(results.endpointResults)}
      </tbody>
    </table>

    <h2>状态码分布</h2>
    <table>
      <thead>
        <tr>
          <th>状态码</th>
          <th>次数</th>
          <th>百分比</th>
          <th>分布</th>
        </tr>
      </thead>
      <tbody>
        ${generateStatusCodeRows(results.statusCodes, results.totalRequests)}
      </tbody>
    </table>

    <div class="meta-info">
      <p>测试时间: ${results.timestamp}</p>
    </div>
  </div>

  <script>
    // 可以添加一些交互性JavaScript
  </script>
</body>
</html>
      `
    }

    // 保存HTML报告
    fs.writeFileSync(path.join(__dirname, config.outputFile), html, 'utf8')
    console.log(`报告已生成: ${config.outputFile}`)
  } catch (error) {
    console.error('生成报告失败:', error)
  }
}

// 获取成功率的CSS类
function getSuccessRateClass(rate) {
  if (isNaN(rate)) return ''
  if (rate >= 95) return 'success'
  if (rate >= 80) return 'warning'
  return 'danger'
}

// 生成端点表格行
function generateEndpointRows(endpointResults) {
  let rows = ''

  if (!endpointResults || Object.keys(endpointResults).length === 0) {
    return '<tr><td colspan="5" style="text-align: center;">无端点数据</td></tr>'
  }

  for (const [endpoint, data] of Object.entries(endpointResults)) {
    // 避免除以零
    const successRate =
      data.totalRequests > 0 ? (data.success / data.totalRequests) * 100 : 0
    const formatValidRate =
      data.formatValid + data.formatInvalid > 0
        ? (data.formatValid / (data.formatValid + data.formatInvalid)) * 100
        : 0

    // 检查平均响应时间是否有效
    const avgDuration =
      !isNaN(data.averageDuration) && data.averageDuration > 0
        ? `${data.averageDuration.toFixed(2)} ms`
        : 'N/A'

    rows += `
      <tr>
        <td>${endpoint}</td>
        <td>${data.totalRequests}</td>
        <td class="${getSuccessRateClass(successRate)}">${successRate.toFixed(2)}%</td>
        <td class="${getSuccessRateClass(formatValidRate)}">${formatValidRate.toFixed(2)}%</td>
        <td>${avgDuration}</td>
      </tr>
    `
  }

  return rows
}

// 生成状态码表格行
function generateStatusCodeRows(statusCodes, totalRequests) {
  let rows = ''

  if (!statusCodes || Object.keys(statusCodes).length === 0) {
    return '<tr><td colspan="4" style="text-align: center;">无状态码数据</td></tr>'
  }

  for (const [code, count] of Object.entries(statusCodes)) {
    const percentage = totalRequests > 0 ? (count / totalRequests) * 100 : 0
    const barWidth = Math.max(percentage, 1) // 至少显示1%宽度

    rows += `
      <tr>
        <td>${code}</td>
        <td>${count}</td>
        <td>${percentage.toFixed(2)}%</td>
        <td>
          <div class="progress-bar">
            <div class="progress-fill" style="width: ${barWidth}%"></div>
          </div>
        </td>
      </tr>
    `
  }

  return rows
}

// 执行报告生成
generateReport()
